/**
 * AnimationManager - 动画管理器
 * 管理多个动画的播放、切换和状态
 */

import { Animation } from './Animation'

export interface AnimationTransition {
  from: string
  to: string
  condition?: () => boolean
  priority?: number
}

export class AnimationManager {
  private animations: Map<string, Animation> = new Map()
  private currentAnimation: Animation | null = null
  private transitions: AnimationTransition[] = []
  private defaultAnimation: string | null = null

  /**
   * 添加动画
   */
  addAnimation(animation: Animation): void {
    this.animations.set(animation.name, animation)
    
    // 如果是第一个动画，设为默认动画
    if (this.animations.size === 1) {
      this.defaultAnimation = animation.name
    }
  }

  /**
   * 移除动画
   */
  removeAnimation(name: string): void {
    const animation = this.animations.get(name)
    if (animation) {
      if (this.currentAnimation === animation) {
        this.currentAnimation = null
      }
      this.animations.delete(name)
    }
  }

  /**
   * 播放指定动画
   */
  play(name: string, force: boolean = false): boolean {
    const animation = this.animations.get(name)
    if (!animation) {
      console.warn(`Animation "${name}" not found`)
      return false
    }

    // 如果已经在播放相同动画且不强制切换，则不做任何操作
    if (this.currentAnimation === animation && !force) {
      return true
    }

    // 停止当前动画
    if (this.currentAnimation) {
      this.currentAnimation.stop()
    }

    // 播放新动画
    this.currentAnimation = animation
    animation.play()
    return true
  }

  /**
   * 停止当前动画
   */
  stop(): void {
    if (this.currentAnimation) {
      this.currentAnimation.stop()
      this.currentAnimation = null
    }
  }

  /**
   * 暂停当前动画
   */
  pause(): void {
    if (this.currentAnimation) {
      this.currentAnimation.pause()
    }
  }

  /**
   * 恢复当前动画
   */
  resume(): void {
    if (this.currentAnimation) {
      this.currentAnimation.play()
    }
  }

  /**
   * 更新动画管理器
   */
  update(deltaTime: number): void {
    // 检查动画转换
    this.checkTransitions()

    // 更新当前动画
    if (this.currentAnimation) {
      this.currentAnimation.update(deltaTime)
      
      // 如果动画完成且不循环，尝试播放默认动画
      if (this.currentAnimation.isFinished() && this.defaultAnimation) {
        this.play(this.defaultAnimation)
      }
    } else if (this.defaultAnimation) {
      // 如果没有当前动画，播放默认动画
      this.play(this.defaultAnimation)
    }
  }

  /**
   * 渲染当前动画
   */
  render(
    ctx: CanvasRenderingContext2D,
    x: number,
    y: number,
    width?: number,
    height?: number
  ): void {
    if (this.currentAnimation) {
      this.currentAnimation.render(ctx, x, y, width, height)
    }
  }

  /**
   * 添加动画转换规则
   */
  addTransition(transition: AnimationTransition): void {
    this.transitions.push(transition)
    // 按优先级排序（高优先级在前）
    this.transitions.sort((a, b) => (b.priority || 0) - (a.priority || 0))
  }

  /**
   * 移除动画转换规则
   */
  removeTransition(from: string, to: string): void {
    this.transitions = this.transitions.filter(
      t => !(t.from === from && t.to === to)
    )
  }

  /**
   * 设置默认动画
   */
  setDefaultAnimation(name: string): void {
    if (this.animations.has(name)) {
      this.defaultAnimation = name
    }
  }

  /**
   * 获取当前动画名称
   */
  getCurrentAnimationName(): string | null {
    return this.currentAnimation?.name || null
  }

  /**
   * 获取当前动画
   */
  getCurrentAnimation(): Animation | null {
    return this.currentAnimation
  }

  /**
   * 获取动画
   */
  getAnimation(name: string): Animation | null {
    return this.animations.get(name) || null
  }

  /**
   * 检查是否有指定动画
   */
  hasAnimation(name: string): boolean {
    return this.animations.has(name)
  }

  /**
   * 获取所有动画名称
   */
  getAnimationNames(): string[] {
    return Array.from(this.animations.keys())
  }

  /**
   * 检查当前动画是否正在播放
   */
  isPlaying(name?: string): boolean {
    if (name) {
      const animation = this.animations.get(name)
      return animation?.isPlaying() || false
    }
    return this.currentAnimation?.isPlaying() || false
  }

  /**
   * 清除所有动画
   */
  clear(): void {
    this.stop()
    this.animations.clear()
    this.transitions = []
    this.defaultAnimation = null
  }

  /**
   * 检查动画转换条件
   */
  private checkTransitions(): void {
    if (!this.currentAnimation) return

    const currentName = this.currentAnimation.name

    for (const transition of this.transitions) {
      if (transition.from === currentName) {
        // 检查转换条件
        if (!transition.condition || transition.condition()) {
          this.play(transition.to)
          break
        }
      }
    }
  }

  /**
   * 创建简单的状态机动画管理器
   */
  static createStateMachine(animations: Animation[], defaultState: string): AnimationManager {
    const manager = new AnimationManager()
    
    animations.forEach(animation => {
      manager.addAnimation(animation)
    })
    
    manager.setDefaultAnimation(defaultState)
    return manager
  }
}